<template>
  <el-dialog
    v-model="dialogVisible"
    title="考试详情"
    width="50%"
    :before-close="handleClose"
    class="detail-dialog"
  >
    <div v-if="exam" class="exam-detail">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="标题">
          {{ exam.title }}
        </el-descriptions-item>
        <el-descriptions-item label="描述">
          <div class="description-content">
            {{ exam.description || '暂无描述' }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="考试日期">
          {{ formatDate(exam.exam_date) }}
        </el-descriptions-item>
        <el-descriptions-item label="考场">
          {{ exam.classroom || '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="座位安排">
          {{ formatSeatingType(exam.seating_type) }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(exam.status)">
            {{ getStatusText(exam.status) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 附件列表 -->
      <div v-if="exam.attachments && exam.attachments.length > 0" class="attachments-section">
        <h4>考试附件：</h4>
        <el-card shadow="never" class="attachment-list">
          <div v-for="attachment in exam.attachments"
               :key="attachment.id"
               class="attachment-item">
            <el-link
              :href="attachment.file_path"
              :download="getFileName(attachment.file_path)"
              type="primary"
              target="_blank">
              <el-icon class="document-icon"><Document /></el-icon>
              <span class="file-name">{{ getFileName(attachment.file_path) }}</span>
              <span class="file-info">
                ({{ formatFileType(attachment.file_type) }} -
                {{ formatDate(attachment.uploaded_at) }})
              </span>
            </el-link>
          </div>
        </el-card>
      </div>

      <!-- 答案附件 -->
      <div v-if="exam.answer_attachments && exam.answer_attachments.length > 0 &&userInfo.role === 'teacher'" class="attachments-section">
        <h4>答案附件（仅教师可见）：</h4>
        <el-card shadow="never" class="attachment-list" >
          <div v-for="attachment in exam.answer_attachments"
               :key="attachment.id"
               class="attachment-item">
            <el-link
              :href="attachment.file_path"
              :download="getFileName(attachment.file_path)"
              type="danger"
              target="_blank">
              <el-icon class="document-icon"><Document /></el-icon>
              <span class="file-name">{{ getFileName(attachment.file_path) }}</span>
              <span class="file-info">
                ({{ formatFileType(attachment.file_type) }} -
                {{ formatDate(attachment.uploaded_at) }})
              </span>
            </el-link>
          </div>
        </el-card>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import { Document } from '@element-plus/icons-vue'
import axios from "axios";
import {ElMessage} from "element-plus";

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  exam: {
    type: Object,
    required: true
  },
    courseId: {
    type: [String, Number],
    required: true
  }
})

const emit = defineEmits(['update:visible', 'close'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}`
}

const formatSeatingType = (seatingType) => {
  if (!seatingType) return '未设置'
  return typeof seatingType === 'string' ? seatingType : (Array.isArray(seatingType) ? seatingType.join(', ') : '未设置')
}

const getFileName = (path) => {
  if (!path) return ''
  const decodedPath = decodeURIComponent(path)
  return decodedPath.split('/').pop()
}

const formatFileType = (fileType) => {
  const typeMap = {
    'video/mp4': '视频',
    'application/pdf': 'PDF',
    'application/msword': 'Word',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'Word',
    'image/jpeg': '图片',
    'image/png': '图片'
  }
  return typeMap[fileType] || '文件'
}

const getStatusType = (status) => {
  const statusMap = {
    'NOT_STARTED': 'info',
    'IN_PROGRESS': 'warning',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'NOT_STARTED': '未开始',
    'IN_PROGRESS': '进行中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || '未知状态'
}

const userInfo = ref({
  role: ''
})

const fetchUserInfo = async () => {
  try {
    const response = await axios.get('/backend/api/account/profile/', {
      withCredentials: true
    })
    if (response.status === 200) {
      userInfo.value = response.data
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败，请稍后重试')
  }
}


onMounted(() => {

    fetchUserInfo()

})

const handleClose = () => {
  emit('close')
}
</script>

<style scoped>
.detail-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.exam-detail {
  padding: 20px;
}

.description-content {
  white-space: pre-wrap;
  line-height: 1.5;
}

.attachments-section {
  margin-top: 20px;
}

.attachments-section h4 {
  color: #606266;
  margin-bottom: 10px;
}

.attachment-list {
  background-color: #f8f9fa;
}

.attachment-item {
  padding: 12px;
  display: flex;
  align-items: center;
}

.attachment-item:not(:last-child) {
  border-bottom: 1px solid #ebeef5;
}

.document-icon {
  margin-right: 8px;
  font-size: 16px;
}

.file-name {
  margin-right: 8px;
  font-weight: 500;
}

.file-info {
  color: #909399;
  font-size: 0.9em;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 20px;
}
</style>